const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3002;

// 中间件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 初始化数据库
const adapter = new FileSync(path.join(__dirname, 'database.json'));
const db = low(adapter);

// 初始化数据库结构
db.defaults({
  books: [
    {
      id: 1,
      isbn: '978-0123456789',
      title: '区块链技术指南',
      author: '张三',
      price: 0.1,
      amount: 100,
      sold_amount: 25,
      status: 'active',
      description: '深入浅出地介绍区块链技术的原理和应用',
      content_hash: 'QmTestContentHash123456789',
      created_at: new Date().toISOString()
    },
    {
      id: 2,
      isbn: '978-9876543210',
      title: 'Web3开发实战',
      author: '李四',
      price: 0.15,
      amount: 50,
      sold_amount: 10,
      status: 'active',
      description: '从零开始学习Web3开发，包含实战项目',
      content_hash: 'QmTestContentHash987654321',
      created_at: new Date().toISOString()
    },
    {
      id: 3,
      isbn: '978-1111111111',
      title: 'NFT艺术与投资',
      author: '王五',
      price: 0.08,
      amount: 120,
      sold_amount: 30,
      status: 'active',
      description: 'NFT艺术品的创作、交易和投资指南',
      content_hash: 'QmTestContentHash111111111',
      created_at: new Date().toISOString()
    }
  ],
  users: [],
  orders: []
}).write();

console.log('✅ 数据库初始化完成');

// 工具函数
function generateId(collection) {
  const items = db.get(collection).value();
  return items.length > 0 ? Math.max(...items.map(item => item.id)) + 1 : 1;
}

// API 路由

// 获取所有图书
app.get('/api/books', (req, res) => {
  try {
    const books = db.get('books').value();
    res.json({
      success: true,
      data: books
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取单本图书
app.get('/api/books/:id', (req, res) => {
  try {
    const { id } = req.params;
    const book = db.get('books').find({ id: parseInt(id) }).value();
    
    if (!book) {
      res.status(404).json({ error: '图书不存在' });
      return;
    }
    
    res.json({
      success: true,
      data: book
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 添加图书
app.post('/api/books', (req, res) => {
  try {
    const { isbn, title, author, price, amount, description, content_hash, metadata_hash, preview_hash } = req.body;
    
    if (!isbn || !title || !author || !price || !amount) {
      res.status(400).json({ error: '缺少必要字段' });
      return;
    }

    // 检查ISBN是否已存在
    const existingBook = db.get('books').find({ isbn }).value();
    if (existingBook) {
      res.status(400).json({ error: 'ISBN已存在' });
      return;
    }

    const newBook = {
      id: generateId('books'),
      isbn,
      title,
      author,
      price,
      amount,
      sold_amount: 0,
      status: 'pending',
      description: description || '',
      content_hash: content_hash || '',
      metadata_hash: metadata_hash || '',
      preview_hash: preview_hash || '',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString()
    };

    db.get('books').push(newBook).write();
    
    res.json({
      success: true,
      data: newBook,
      message: '图书添加成功'
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新图书
app.put('/api/books/:id', (req, res) => {
  try {
    const { id } = req.params;
    const { title, author, price, amount, description, status } = req.body;
    
    const book = db.get('books').find({ id: parseInt(id) }).value();
    if (!book) {
      res.status(404).json({ error: '图书不存在' });
      return;
    }

    db.get('books')
      .find({ id: parseInt(id) })
      .assign({
        title: title || book.title,
        author: author || book.author,
        price: price !== undefined ? price : book.price,
        amount: amount !== undefined ? amount : book.amount,
        description: description || book.description,
        status: status || book.status,
        updated_at: new Date().toISOString()
      })
      .write();
    
    res.json({
      success: true,
      message: '图书更新成功'
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 删除图书
app.delete('/api/books/:id', (req, res) => {
  try {
    const { id } = req.params;
    const book = db.get('books').find({ id: parseInt(id) }).value();
    
    if (!book) {
      res.status(404).json({ error: '图书不存在' });
      return;
    }

    db.get('books').remove({ id: parseInt(id) }).write();
    
    res.json({
      success: true,
      message: '图书删除成功'
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 用户相关API

// 获取或创建用户
app.post('/api/users', (req, res) => {
  try {
    const { wallet_address, username } = req.body;
    
    if (!wallet_address) {
      res.status(400).json({ error: '钱包地址不能为空' });
      return;
    }

    // 查询用户是否存在
    let user = db.get('users').find({ wallet_address }).value();
    
    if (user) {
      res.json({
        success: true,
        data: user,
        message: '用户已存在'
      });
    } else {
      // 创建新用户
      user = {
        id: generateId('users'),
        wallet_address,
        username: username || '',
        created_at: new Date().toISOString()
      };
      
      db.get('users').push(user).write();
      
      res.json({
        success: true,
        data: user,
        message: '用户创建成功'
      });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取用户订单
app.get('/api/users/:wallet_address/orders', (req, res) => {
  try {
    const { wallet_address } = req.params;
    
    const user = db.get('users').find({ wallet_address }).value();
    if (!user) {
      res.status(404).json({ error: '用户不存在' });
      return;
    }

    const orders = db.get('orders')
      .filter({ user_id: user.id })
      .map(order => {
        const book = db.get('books').find({ id: order.book_id }).value();
        return {
          ...order,
          title: book ? book.title : '',
          author: book ? book.author : '',
          isbn: book ? book.isbn : ''
        };
      })
      .value();
    
    res.json({
      success: true,
      data: orders
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 创建订单
app.post('/api/orders', (req, res) => {
  try {
    const { wallet_address, book_id, quantity, total_price, transaction_hash, token_code } = req.body;
    
    if (!wallet_address || !book_id || !quantity || !total_price) {
      res.status(400).json({ error: '缺少必要字段' });
      return;
    }

    const user = db.get('users').find({ wallet_address }).value();
    if (!user) {
      res.status(404).json({ error: '用户不存在' });
      return;
    }

    const newOrder = {
      id: generateId('orders'),
      user_id: user.id,
      book_id: parseInt(book_id),
      quantity: parseInt(quantity),
      total_price: parseFloat(total_price),
      transaction_hash: transaction_hash || '',
      token_code: token_code || '',
      status: 'completed',
      created_at: new Date().toISOString()
    };

    db.get('orders').push(newOrder).write();
    
    // 更新图书销售数量
    db.get('books')
      .find({ id: parseInt(book_id) })
      .update('sold_amount', n => n + parseInt(quantity))
      .write();
    
    res.json({
      success: true,
      data: newOrder,
      message: '订单创建成功'
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 统计信息API
app.get('/api/stats', (req, res) => {
  try {
    const books = db.get('books').value();
    const users = db.get('users').value();
    const orders = db.get('orders').value();
    
    const totalSales = orders
      .filter(order => order.status === 'completed')
      .reduce((sum, order) => sum + order.total_price, 0);

    const stats = {
      total_books: books.length,
      total_sales: totalSales,
      total_users: users.length,
      total_orders: orders.length
    };
    
    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: '后端服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 后端服务启动成功！`);
  console.log(`📍 服务地址: http://localhost:${PORT}`);
  console.log(`📊 API文档: http://localhost:${PORT}/api/health`);
  console.log(`💾 数据存储: JSON文件 (${path.join(__dirname, 'database.json')})`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n正在关闭服务器...');
  console.log('数据已保存到JSON文件');
  process.exit(0);
}); 